import { saveAs } from 'file-saver';
import { WordExportOptions, ExportResult, ExportProgress, DEFAULT_WORD_OPTIONS } from './types';

export class WordExportServiceSimple {
  private progressCallback?: (progress: ExportProgress) => void;

  constructor(progressCallback?: (progress: ExportProgress) => void) {
    this.progressCallback = progressCallback;
  }

  /**
   * 导出内容为RTF文档（兼容Word）
   */
  async exportToWord(
    content: string,
    options: Partial<WordExportOptions> = {},
    filename?: string
  ): Promise<ExportResult> {
    try {
      const fullOptions = { ...DEFAULT_WORD_OPTIONS, ...options };
      const finalFilename = filename || this.generateFilename();

      this.reportProgress('preparing', 0, '准备导出内容...');

      // 解析Markdown内容
      const parsedContent = this.parseMarkdown(content);

      this.reportProgress('converting', 25, '转换内容格式...');

      // 创建RTF文档内容
      const rtfContent = this.createRTFDocument(parsedContent, fullOptions, finalFilename);

      this.reportProgress('generating', 50, '生成Word文档...');

      // 创建Blob
      const blob = new Blob([rtfContent], { 
        type: 'application/rtf' 
      });

      this.reportProgress('saving', 75, '保存Word文件...');

      // 保存文件（使用.doc扩展名以确保Word能打开）
      saveAs(blob, `${finalFilename}.doc`);

      this.reportProgress('completed', 100, '导出完成');

      return {
        success: true,
        filename: `${finalFilename}.doc`,
        size: blob.size
      };

    } catch (error) {
      console.error('[WordExportServiceSimple] 导出失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '导出失败'
      };
    }
  }

  /**
   * 解析Markdown内容为结构化数据
   */
  private parseMarkdown(content: string): ParsedElement[] {
    const elements: ParsedElement[] = [];
    const lines = content.split('\n');
    let currentList: string[] = [];
    let inCodeBlock = false;
    let codeBlockContent: string[] = [];

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];

      // 处理代码块
      if (line.startsWith('```')) {
        if (!inCodeBlock) {
          inCodeBlock = true;
          codeBlockContent = [];
        } else {
          inCodeBlock = false;
          elements.push({
            type: 'codeblock',
            content: codeBlockContent.join('\n')
          });
          codeBlockContent = [];
        }
        continue;
      }

      if (inCodeBlock) {
        codeBlockContent.push(line);
        continue;
      }

      // 处理列表
      if (line.match(/^[-*+]\s+/)) {
        currentList.push(line.replace(/^[-*+]\s+/, ''));
        continue;
      } else if (currentList.length > 0) {
        elements.push({
          type: 'list',
          items: [...currentList]
        });
        currentList = [];
      }

      // 处理标题
      const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
      if (headingMatch) {
        elements.push({
          type: 'heading',
          level: headingMatch[1].length as 1 | 2 | 3 | 4 | 5 | 6,
          content: headingMatch[2]
        });
        continue;
      }

      // 处理段落
      if (line.trim()) {
        elements.push({
          type: 'paragraph',
          content: line
        });
      } else {
        // 空行
        elements.push({
          type: 'paragraph',
          content: ''
        });
      }
    }

    // 处理剩余的列表
    if (currentList.length > 0) {
      elements.push({
        type: 'list',
        items: currentList
      });
    }

    return elements;
  }

  /**
   * 创建RTF文档内容
   */
  private createRTFDocument(elements: ParsedElement[], options: WordExportOptions, title: string): string {
    const fontSize = Math.round(options.fontSize * 2); // RTF字体大小单位是半点
    const lineSpacing = Math.round(options.lineSpacing * 240); // RTF行间距单位

    let rtf = '{\\rtf1\\ansi\\deff0';
    
    // 字体表
    rtf += '{\\fonttbl{\\f0 Times New Roman;}{\\f1 SimSun;}}';
    
    // 颜色表
    rtf += '{\\colortbl;\\red0\\green0\\blue0;\\red255\\green0\\blue0;}';
    
    // 文档格式
    rtf += `\\paperw11906\\paperh16838`; // A4纸张
    rtf += `\\margt${this.mmToTwips(options.margins.top)}`;
    rtf += `\\margr${this.mmToTwips(options.margins.right)}`;
    rtf += `\\margb${this.mmToTwips(options.margins.bottom)}`;
    rtf += `\\margl${this.mmToTwips(options.margins.left)}`;
    
    // 文档标题
    rtf += `\\f1\\fs${fontSize + 8}\\b ${this.escapeRTF(title)}\\b0\\par\\par`;
    
    // 处理内容元素
    for (const element of elements) {
      switch (element.type) {
        case 'heading':
          const headingSize = fontSize + (7 - (element.level || 1)) * 4;
          rtf += `\\f1\\fs${headingSize}\\b ${this.escapeRTF(element.content || '')}\\b0\\par\\par`;
          break;
        case 'paragraph':
          if ((element.content || '').trim()) {
            const formattedContent = this.formatInlineText(element.content || '');
            rtf += `\\f1\\fs${fontSize}\\sl${lineSpacing}\\slmult1 ${formattedContent}\\par\\par`;
          } else {
            rtf += '\\par';
          }
          break;
        case 'list':
          for (const item of (element.items || [])) {
            const formattedItem = this.formatInlineText(item);
            rtf += `\\f1\\fs${fontSize}\\sl${lineSpacing}\\slmult1\\li720 \\bullet\\tab ${formattedItem}\\par`;
          }
          rtf += '\\par';
          break;
        case 'codeblock':
          rtf += `\\f0\\fs${fontSize - 4}\\cf1 ${this.escapeRTF(element.content || '')}\\cf0\\par\\par`;
          break;
      }
    }
    
    // 页脚
    if (options.headerFooter?.footer) {
      rtf += `{\\footer\\pard\\qc\\f1\\fs${fontSize - 4} ${this.escapeRTF(options.headerFooter.footer)}}`;
    }
    
    rtf += '}';
    return rtf;
  }

  /**
   * 格式化内联文本（粗体、斜体等）
   */
  private formatInlineText(text: string): string {
    let formatted = this.escapeRTF(text);
    
    // 处理粗体 **text**
    formatted = formatted.replace(/\*\*(.*?)\*\*/g, '\\b $1\\b0');
    
    // 处理斜体 *text*
    formatted = formatted.replace(/\*(.*?)\*/g, '\\i $1\\i0');
    
    // 处理行内代码 `text`
    formatted = formatted.replace(/`(.*?)`/g, '\\f0 $1\\f1');
    
    return formatted;
  }

  /**
   * 转义RTF特殊字符
   */
  private escapeRTF(text: string): string {
    return text
      .replace(/\\/g, '\\\\')
      .replace(/\{/g, '\\{')
      .replace(/\}/g, '\\}')
      .replace(/[\u0080-\uFFFF]/g, (match) => {
        return `\\u${match.charCodeAt(0)}?`;
      });
  }

  /**
   * 将毫米转换为Twips（RTF单位）
   */
  private mmToTwips(mm: number): number {
    return Math.round(mm * 56.692913386);
  }

  /**
   * 生成文件名
   */
  private generateFilename(): string {
    const now = new Date();
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0');
    return `文档_${timestamp}`;
  }

  /**
   * 报告导出进度
   */
  private reportProgress(stage: ExportProgress['stage'], progress: number, message: string): void {
    if (this.progressCallback) {
      this.progressCallback({ stage, progress, message });
    }
  }
}

// 解析后的元素类型
interface ParsedElement {
  type: 'heading' | 'paragraph' | 'list' | 'codeblock';
  content?: string;
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  items?: string[];
}